<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>viem + MetaMask Demo</title>
</head>

<body>
  <button id="connect">Connect MetaMask</button>
  <button id="send">Send Tx</button>

  <script type="module">
    import { createWalletClient, custom } from "https://esm.sh/viem";
    import { sepolia } from "https://esm.sh/viem/chains";

    let client;

    document.getElementById("connect").onclick = async () => {
      if (!window.ethereum) {
        alert("MetaMask not detected!");
        return;
      }

      // 请求授权
      await window.ethereum.request({ method: "eth_requestAccounts" });


      // 用 eth_accounts 拿当前账号
      const [address] = await window.ethereum.request({ method: "eth_accounts" });

      console.log("MetaMask address:", address);
      const chainId = await window.ethereum.request({ method: "eth_chainId" });
      console.log("当前链 ID:", chainId);
      // 创建 client
      const metamaskChain = {
        id: Number(chainId),
        name: "MetaMask Current Chain",
        nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
        rpcUrls: { default: { http: [""] } }, // 这里可以随便写，MetaMask 会接管
      };

      client = createWalletClient({
        account: address,
        chain: metamaskChain,
        transport: custom(window.ethereum),
      });


      console.log("Connected via MetaMask:", client.account.address);
      alert("Connected: " + client.account.address);
    };

    document.getElementById("send").onclick = async () => {
      if (!client) {
        alert("Please connect first!");
        return;
      }

      // 发送一笔交易 (给自己转 0.001 ETH)
      const hash = await client.sendTransaction({
        to: client.account.address,
        value: 1000000000000000n, // 0.001 ETH
      });

      console.log("Tx sent:", hash);
      alert("Tx hash: " + hash);
    };
  </script>
</body>

</html>